using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using OrderService.Grpc.Services;
using OrderService.Infrastructure;
using SharedKernel.Infrastructure.Comm;
using SharedKernel.Infrastructure.EventBus;
using SharedKernel.Infrastructure.EventBus.RabbitMQ;
using SharedKernel.Infrastructure.Grpc.Interceptors;
using SharedKernel.Infrastructure.Grpc.Options;
using SharedKernel.Infrastructure.Redis;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using OrderService.Application;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        var configuration = builder.Configuration;
        // Add services to the container.
        // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
        builder.Services.AddControllers();

        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();
        //注册延迟加载
        builder.Services.AddTransient(typeof(Lazy<>));
        //注册Http上下文访问器
        builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        //注册用户上下文
        builder.Services.AddScoped<IUserContext, UserContext>();
        // 添加缓存
        builder.Services.AddCache(builder.Configuration, "Redis");

        #region 注册领域相关的服务
        //注册基础服务
        builder.Services.AddInfrastructure(builder.Configuration);
        //注册应用服务
        builder.Services.AddApplication();
        #endregion

        //注册Jwt验证
        builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = builder.Configuration["Jwt:Issuer"],
                    ValidAudience = builder.Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
                };
            });

        builder.Services.AddSwaggerGen();
        builder.Services.AddAuthorization();

        //注入Grpc配置文件
        builder.Services.Configure<GrpcClientOptions>(configuration.GetSection("GrpcClients:OrderServiceGrpc"));
        //注入Grpc
        builder.Services.AddGrpc(options =>
        {
            // 添加全局拦截器（按注册顺序执行）
            options.Interceptors.Add<GrpcServiceAuthorizationInterceptor>();
            // 可添加多个拦截器（如日志、限流、缓存等）
            // options.Interceptors.Add<AnotherInterceptor>();
        }); 
        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.MapOpenApi();
        }

        app.UseHttpsRedirection();

        app.UseAuthentication();
        app.UseAuthorization();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseInfrastructure();
        app.MapControllers();
        app.MapGrpcService<OrderGrpcServiceImpl>();
        app.Run();
    }
}